﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.XPath;
using OTS.BLL;

/// <summary>
/// Summary description for CommonMethod
/// </summary>
public class CommonMethod
{
    #region 提示信息
    public static void regAlertMessage(string p_sMessage, System.Web.UI.Page p_pgRequestPage)
    {
        string l_sStartUpScript;
        l_sStartUpScript = "<script language='javascript' type='text/javascript'>alert('" + p_sMessage + "');</script>";
        p_pgRequestPage.ClientScript.RegisterStartupScript(p_pgRequestPage.GetType(), "Startup" + p_sMessage, l_sStartUpScript);
    }
    public static void regAlertMessage(UpdatePanel UPStr, string p_sMessage, System.Web.UI.Page p_pgRequestPage)
    {
        ScriptManager.RegisterStartupScript(UPStr, p_pgRequestPage.GetType(), "onekey", "alert('" + p_sMessage + "');", true);
    }
    public static void regAlertMessageScript(UpdatePanel UPStr, string p_sMessage, System.Web.UI.Page p_pgRequestPage)
    {
        ScriptManager.RegisterStartupScript(UPStr, p_pgRequestPage.GetType(), "onclik", p_sMessage, true);
    }
    #endregion

    #region 获取当前用户对指定页面所拥有的权限
    /// <summary>
    /// 
    /// </summary>
    /// <param name="Temp">Temp[0]:用户编号，Temp[1]:公司编号，Temp[2]:页面类型</param>
    /// <returns>StrTemp[0]:View，StrTemp[1]:Add，StrTemp[2]:Update，StrTemp[3]:Delete, StrTemp[4]:exporte</returns>
    public void GetRight(Page page, string[] Temp, GridView gv, string[] control, int[] gvColumn, string loginUrl)
    {
        bool[] RightTemp = SysRightBLL.GetRightByType(Temp);
        if (!RightTemp[0])
        { page.Response.Write("<script language='javascript'>window.parent.location.href='" + loginUrl + "';</script>"); }

        int j = 1;
        Control tempControl = null;
        foreach (string button in control)
        {
            tempControl = page.FindControl(button);
            if (tempControl != null)
            { tempControl.Visible = RightTemp[j]; }
            j++;
        }
        if (gv != null && gvColumn != null)
        {
            if (gvColumn.Length > 0 && gv.Columns.Count > gvColumn[0])
            {
                gv.Columns[gvColumn[0]].Visible = RightTemp[2];
            }
            if (gvColumn.Length > 1 && gv.Columns.Count >= gvColumn[1])
            {
                gv.Columns[gvColumn[1]].Visible = RightTemp[3];
            }
        }
    }
        
    public void GetRightUnite(Page page, string[] Temp, string[] control, int[] rightType, string loginUrl)
    {
        bool[] RightTemp = SysRightBLL.GetRightByType(Temp);
        if (!RightTemp[0])
        { page.Response.Write("<script language='javascript'>window.parent.location.href='" + loginUrl + "';</script>"); }

        int j = 0;
        Control tempControl = null;
        foreach (string button in control)
        {
            tempControl = page.FindControl(button);
            if (tempControl != null)
            { tempControl.Visible = RightTemp[rightType[j]]; }
            j++;
        }
    } 
    #endregion

    #region Session 超时
    // UserCode超时
    public static void IsTimeOutUserCode(System.Web.UI.Page page)
    {
        if (page.Session["UserCode"] == null)
        { page.Response.Redirect("~/error.aspx"); }
    }
    public static void IsTimeOutUserCode(System.Web.UI.Page page, string urlRedirect)
    {

        if (page.Session["UserCode"] == null)
        { page.Response.Redirect(urlRedirect); }
    }

    // UserCode CoCode超时
    public static void IsTimeOutUserCodeAndCoCode(System.Web.UI.Page page, string urlRedirect)
    {
        if (page.Session["UserCode"] == null || page.Session["CoCode"] == null)
        {
            page.Response.Redirect(urlRedirect);
        }
    }
    public static void IsTimeOutUserCodeAndCoCode(UpdatePanel UPStr, System.Web.UI.Page page, string urlRedirect)
    {
        if (page.Session["UserCode"] == null || page.Session["CoCode"] == null)
        {
            page.Response.Redirect(urlRedirect);
        }
        ScriptManager.RegisterStartupScript(UPStr, page.GetType(), "onekey", "window.parent.location.href='" + urlRedirect + "';", true);
    }

    public static bool IsTimeOutUserCodeAndCoCode(System.Web.UI.Page page)
    {
        if (page.Session["UserCode"] == null || page.Session["CoCode"] == null)
        { return false; }
        return true;
    }
    #endregion

    /// <summary>
    /// 对传递的参数字符串进行处理，防止注入式攻击
    /// </summary>
    /// <param name="str">传递的参数字符串</param>
    /// <returns>String</returns>
    public static string ConvertSql(string str)
    {
        #region
        str = str.Trim();
        str = str.Replace("'", "''");
        str = str.Replace(";--", "");
        str = str.Replace("=", "");
        str = str.Replace(" or ", " ");
        str = str.Replace(" and ", " ");
        str = str.Replace("<", "《");
        str = str.Replace(">", "》");
        str = str.Replace("&amp;", " ");
        str = str.Replace("&", " ");
        return str;
        #endregion
    }

    //
    public static string StrMerge(DataTable dt, string columnName)
    {
        string str = "";
        foreach (DataRow row in dt.Rows)
        {
            str += row[columnName] + "/";
        }
        return str;
    }
    
    //
    public static string ShorStr(string str, int n)
    {
        string temp = null;
        if (str.Length > n)
        {
            temp = str.Substring(0, 17) + "...";
            return temp;
        }
        return str;
    }
    
    public static string GetListNames(ContractModel model, string currentValue, string strID)
    {
        StringBuilder listNames = new StringBuilder();

        if (!string.IsNullOrEmpty(currentValue))
        { listNames.Append(string.Format("<option value=\"{0}\">{0}</option>", currentValue)); }
        if (model.listNamesDT != null && model.listNamesDT.Rows.Count > 0)
        {
            DataRow[] rows = model.listNamesDT.Select(string.Format("ListNameType='{0}' and ListName<>'{1}'", model.ColumnType, currentValue));
            foreach (DataRow row in rows)
            {
                listNames.Append(string.Format("<option value=\"{0}\">{0}</option>", row["ListName"].ToString()));
            }
        }
        return listNames.ToString();
    }
    
    public static int[] GetRowsSatrEnaPosition(DeliveryModel model, int rowsCount)
    {
        if (model.pageSize == null)
        { model.pageSize = model.defaultPageSize; }
        int[] startEndPostion = new int[] { 0, model.pageSize };
        if (model.pageIndex < model.pageNextIndex)
        {
            startEndPostion[0] = ((model.pageNextIndex - model.pageIndex) > 1) ? (model.pageNextIndex - 1) * model.pageSize : model.pageIndex * model.pageSize;
            startEndPostion[1] = model.pageNextIndex * model.pageSize > rowsCount ? rowsCount : model.pageNextIndex * model.pageSize;
        }
        else
        {
            startEndPostion[0] = model.pageNextIndex > 1 ? (model.pageNextIndex - 1) * model.pageSize : 0;
            startEndPostion[1] = model.pageNextIndex > 1 ? model.pageNextIndex * model.pageSize : (model.pageSize > rowsCount ? rowsCount : model.pageSize);
        }
        return startEndPostion;
    }

    //导出DataTable到Excel
    public static void ExportExcel(ExportExcelModel model)
    {
        //model.path = HttpContext.Current.Server.MapPath("~/ExproteTempFile/") + model.path;
        #region html格式写Excel

        StringBuilder sb = new StringBuilder("<html>");
        sb.Append("<head>");
        sb.Append("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>");
        sb.Append("<style type=\"text/css\">");
        sb.Append("td{border:solid 1px black;}");
        sb.Append("</style>");
        sb.Append("</head>");
        sb.Append("<body>");
        sb.Append("<table style='border:solid 1px black;border-collapse:collapse;'><tr>");
        if (model.columnsList != null && model.columnsList.Count > 1 && model.columnsList[1].Count > 0)
        {
            foreach (string tempColumnName in model.columnsList[1])
            {
                sb.Append("<td>");
                sb.Append(tempColumnName);
                sb.Append("</td>");
            }
        }
        else
        {
            foreach (string tempColumnName in model.columnsList[0])
            {
                sb.Append("<td>");
                sb.Append(tempColumnName);
                sb.Append("</td>");
            }
        }
        sb.Append("</tr>");

        if (model.excelDataSourceDT != null)
        {
            #region Table
            if (model.exportAllDT)
            {
                foreach (DataRow row in model.excelDataSourceDT.Rows)
                {
                    sb.Append("<tr>");
                    foreach (string tempColumn in model.columnsList[0])
                    {
                        sb.Append("<td>");
                        sb.Append(row[tempColumn]);
                        sb.Append("</td>");
                    }
                    sb.Append("</tr>");
                }
            }
            else
            {
                for (int i = model.nStart; i < model.nEnd; i++)
                {
                    sb.Append("<tr>");
                    foreach (string tempColumn in model.columnsList[0])
                    {
                        sb.Append("<td>");
                        sb.Append(model.excelDataSourceDT.Rows[i][tempColumn]);
                        sb.Append("</td>");
                    }
                    sb.Append("</tr>");
                }
            }
            #endregion
        }
        else if (model.excelDataRows != null && model.excelDataRows.Length > 0)
        {
            #region DataRows
            foreach (DataRow row in model.excelDataRows)
            {
                sb.Append("<tr>");
                foreach (string tempColumn in model.columnsList[0])
                {
                    sb.Append("<td>");
                    sb.Append(row[tempColumn]);
                    sb.Append("</td>");
                }
                sb.Append("</tr>");
            }
            #endregion
        }

        sb.Append("</table></body></html>");

        StreamWriter sw = new StreamWriter(model.path, false);
        sw.Write(sb.ToString());
        sw.Flush();
        sw.Close();

        #endregion
    }

    public static bool CheckNUM(string str)
    {
        if (string.IsNullOrEmpty(str.Trim()))
        { return false; }
        try
        {
            decimal.Parse(str);
            return true;
        }
        catch
        { return false; }
    }

    /// <summary>
    /// Gets a string value from xml
    /// </summary>
    /// <param name="stringName">The name of the string formatted as a namespace (e.g. Topic.HomePageTitle)</param>
    /// <returns>string value from xml</returns>
    public static string GetString(string stringName)
    {
        XmlDocument xdoc = null;
        // Load the xml containing the strings
        if (xdoc == null)
        {
            xdoc = new XmlDocument();
            xdoc.Load(HttpContext.Current.Server.MapPath("Setting/App.xml"));
        }

        // Build the XPath query
        string xpath = "//TestConfiguration/" + stringName.Replace(".", "/");

        // Try to locate the string
        XPathNavigator foundNavigator = xdoc.CreateNavigator().SelectSingleNode(xpath);

        // If a match was found, return the value - otherwise return an empty string
        if (foundNavigator != null)
        {
            return foundNavigator.Value;
        }

        return String.Empty;
    }
    public static string GetStringSimple(string stringName)
    {
        XmlDocument xdoc = null;
        // Load the xml containing the strings
        if (xdoc == null)
        {
            xdoc = new XmlDocument();
            xdoc.Load(HttpContext.Current.Server.MapPath("Setting/App.xml"));
        }

        return xdoc.SelectSingleNode("//SettingRoot/" + stringName).InnerXml;
    }
    /// <summary>
    /// 返回包含中文字符的字符串长度
    /// C# 的string.Length中中文字只做1位统计,所以要将其转换为2位
    /// </summary>
    /// <param name="strSource">要统计长度的字符串变量</param>
    /// <returns>字符串长度</returns>
    public static int GetLength(string strSource)
    {
        Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
        int nLength = strSource.Length;

        for (int i = 0; i < strSource.Length; i++)
        {
            if (regex.IsMatch(strSource.Substring(i, 1)))
            {
                nLength++;
            }
        }

        return nLength;
    }

}